package com.moyun.syssecurity.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyun.common.enums.CodeEnum;
import com.moyun.model.common.R;
import com.moyun.common.utils.SpringContextUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName MyLogoutSuccessHandler
 * @Description 自定义登出成功处理器，用于登出成功后的处理
 * @Author yangboxuan
 * @Date 2021/5/3 19:10
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    private final ObjectMapper objectMapper;
    private static String ONLINE_USERS = "ONLINE_USERS";

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter out = response.getWriter();
        if (authentication == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.write(this.objectMapper.writeValueAsString(R.error(CodeEnum.FAIL.getCode(), "请先进行登录")));
            out.flush();
            out.close();
            return;
        }

        // 清除缓存中 用户数据
        RedisTemplate redisTemplate = SpringContextUtil.getBean("stringRedisTemplate", RedisTemplate.class);
        redisTemplate.delete(ONLINE_USERS + authentication.getName());


        // 清除cookie中用户数据
        Cookie cookie = new Cookie("jwtToken", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        out.write(objectMapper.writeValueAsString(R.ok(CodeEnum.SUCCESS.getCode(), "登出成功")));
        out.flush();
        out.close();
    }
}
